package cn.kgc.reflect.base;

import cn.kgc.pojo.Book;
import cn.kgc.pojo.User;
import org.apache.commons.beanutils.BeanUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/*
        1 ResultSet
        2 RequestParamtterMap
 */
public class BeanUtisDemo {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, IntrospectionException {
            /*
                    ResultSet rs=xxx;
                    List<User> list=new ArrayList<User>();
                    User user=null;
                    rs.getResultSetMetaData();
                    while(rs.next()){
                        user=new User();
                        user.setUsername(rs.getObject(1);
                        user.setId(rs.getObject(2);
                    }
                findbugs-->
             */
        Book b = new Book();
        User u = new User();
        System.out.println(b);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bid", 1);
        map.put("bookname", "tlbb");
        map.put("stock", 100);
        map.put("price", 3.3);
        map.put("author", "zsf");

        map.put("uid", 999);
        map.put("username", "admin");
        map.put("password", "123456");
        //    BeanUtils.populate(b,map);
        //     System.out.println(b);
        Set<String> set = map.keySet();
        BeanInfo bInfo = Introspector.getBeanInfo(User.class);
        BeanInfo info = Introspector.getBeanInfo(Book.class);
        PropertyDescriptor pds[] = info.getPropertyDescriptors();
        PropertyDescriptor bin[] = bInfo.getPropertyDescriptors();
        for (String x:set){
            BeanUtils.copyProperty(u,x,map.get(x));
        }
        System.out.println(u);
        for (String s : set) {
            for (PropertyDescriptor pd : pds) {
                if (pd.getName().equals(s))
                    BeanUtils.copyProperty(b, s, map.get(s));
            }

        }
        System.out.println(b);
    }

}
